package com.zjw.service.message;

import com.zjw.service.message.impl.SimpleEventLooper;
import com.zjw.service.message.impl.SimpleUserPool;
import com.zjw.service.message.impl.SocketConnectSession;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) {
        IUserPool userPool = new SimpleUserPool();
        MessageTransferService transferService = new MessageTransferService(userPool);
        IEventLooper connectLooper = new SimpleEventLooper();
        try (ServerSocket serverSocket = new ServerSocket(8888)) {
            System.out.println("开始监听");
            connectLooper.loop();
            while (true) {
                Socket accept = serverSocket.accept();
                //处理新连接
                IConnectSession connectSession = new SocketConnectSession(accept);
                connectLooper.registerEvent((IEvent) connectSession);
                connectSession.connect(new IConnectSession.IConnectListener() {
                    private long uid;

                    @Override
                    public void onMessage(IConnectSession session, byte[] bytes) {
                        //transferService.transferTo(MessageFactory.fromByte(bytes));
                        String msg = new String(bytes, StandardCharsets.UTF_8);
                        System.out.println(msg);
                        //解析消息，如果是请求连接消息
                        //uid = session.parse.uid
                        //userPool.connect(uid, session);
                        session.writeBytes(("this is from service replay:" + msg).getBytes(StandardCharsets.UTF_8));
                    }

                    @Override
                    public void onMessage(IConnectSession session, Message message) {

                    }

                    @Override
                    public void onClose(IConnectSession session) {
                        userPool.disconnect(uid);
                        connectLooper.unregisterEvent((IEvent) session);
                    }

                    @Override
                    public void onConnect(IConnectSession session) {
                        System.out.println("connect size " + userPool.size());
                    }

                    @Override
                    public void onError(IConnectSession session, Throwable error) {
                        System.out.println(error);
                    }
                });
            }
        } catch (IOException e) {
            System.err.println(e);
        }

    }

}
